<template>
  <div class="article-list">
    <ul class="list" v-loading="loading">
      <li
        class="article-wrapper"
        v-for="(item, index) in Articles"
        :key="index"
      >
        <ArticleCard :article="item" />
      </li>
      <div v-if="!hasMore" @click="loadMoreArticle" class="no-more">
        没有更多数据了
      </div>
      <div v-else class="load-more" @click="loadMoreArticle">
        <i class="el-icon-bottom"></i>
        加载更多
      </div>
    </ul>
  </div>
</template>

<script>
import getAllArticles from '@/mock/articles.js'
import ArticleCard from '@/components/Article/ArticleCard'
import InfiniteScroll from 'vue-infinite-scroll'
import { getArticleList } from '../../api/modules/article'

export default {
  data() {
    return {
      Articles: [],
      loading: false,
      hasMore: true,
      limit: 8,
      page: 1,
      isSwitchTag: false,
      tagId: 0
    }
  },
  components: {
    ArticleCard
  },
  directives: {
    InfiniteScroll
  },
  mounted() {
    // 获取文章
    this.$nextTick(() => {
      this.loadMoreArticle()
      this.$bus.$on('SwitchListByTagId', this.getArticleListByTag)
    })
  },
  beforeDestroy() {
    this.$bus.$off('SwitchListByTagId', this.getArticleListByTag)
  },
  methods: {
    // // 判断是否滚动到底部
    // isScrollBottom () {
    //   const scrollContainer = document.documentElement; // 修改为实际的滚动容器，例如页面根元素或指定的滚动容器元素
    //   return scrollContainer.scrollTop + scrollContainer.clientHeight >= scrollContainer.scrollHeight;
    // },
    // 加载更多文章
    async loadMoreArticle() {
      if (this.loading || !this.hasMore) return
      const { limit, page } = this
      this.loading = true
      let res
      // 通过是否选择了指定标签变换列表
      if (this.isSwitchTag) {
        res = await this.$API.article.getArticleByTagId(this.tagId, limit, page)
      } else {
        res = await this.$API.article.getArticleList(this.limit, this.page)
      }
      if (!res.data) {
        this.loading = false
        this.hasMore = false
      }
      if (res.status === 200) {
        const newArticles = res.data.payload
        this.Articles.push(...newArticles)
        this.page++
        this.loading = false
      }
    },
    // 通过tagId获取文章
    async getArticleListByTag(id) {
      this.page = 1
      const { limit, page } = this
      let res
      console.log(id)
      // 全部标签或指定标签
      if (id == 'all') {
        this.isSwitchTag = false
        res = await this.$API.article.getArticleList(limit, page)
      } else {
        this.isSwitchTag = true
        this.tagId = id
        res = await this.$API.article.getArticleByTagId(id, limit, page)
      }
      console.log(res)
      if (!res.data) this.Articles = []
      if (res.status == 200) {
        this.Articles = res.data.payload
      }
    }
  }
}
</script>

<style scoped src="@/assets/style/modules/article/articleList.css">
</style>
